import asyncio

from fastapi import APIRouter

from app.xueqiu.apis import *
from app.xueqiu.items import *
from app.xueqiu.mongo_cols import *
from standard_response import StandardResponseItem
from utils import chrome_version

STOCKS_NAMES_REF = {}

router = APIRouter(prefix='/xueqiu/api')


async def get_stock_name(stock_code: str) -> str:
    if STOCKS_NAMES_REF.get(stock_code):
        return STOCKS_NAMES_REF[stock_code]

    item = await STOCKS_NAMES_COL.find_one({"stock_code": stock_code})
    if item:
        STOCKS_NAMES_REF[stock_code] = item['stock_name']
        return item['stock_name']

    cookies = await get_cookies()
    async with AsyncSession(impersonate="chrome110", cookies=cookies) as session:
        data = await suggest_stock(session, stock_code)
        name = data[0]['query']

    STOCKS_NAMES_REF[stock_code] = name
    data = {"stock_code": stock_code, "stock_name": name}
    await STOCKS_NAMES_COL.update_one(data, {"$set": data}, upsert=True)
    return name


async def get_cookies():
    item = await COOKIES_COL.find_one({})
    return {
        "xq_a_token": item['xq_a_token'],
        "xq_r_token": item['xq_r_token'],
    }


@router.get("/set_cookies")
async def set_cookies(curl_str: str):
    def get_token():
        for i in curl_str.split("-H"):
            if 'cookie' in i:
                for line in i.replace("'", '').split(": ")[-1].split("; "):
                    key, val = line.split("=", 1)
                    if key.lower() in ["xq_a_token", "xq_r_token"]:
                        yield key.lower(), val

    cookies = {k: v for k, v in get_token()}
    await COOKIES_COL.delete_many({})
    await COOKIES_COL.insert_one(cookies)
    cookies.pop("_id", None)
    return StandardResponseItem(data=cookies)


@router.post("/set_stocks")
async def set_stocks(item: SetStocksItem):
    # 设置关注股票
    for stock in item.stocks:
        await ATTENTION_STOCKS_COL.update_one({'stock_code': stock}, {'$set': {'stock': stock}}, upsert=True)
    return StandardResponseItem()


@router.delete('/remove_stock')
async def remove_stock(stock_code: str):
    await ATTENTION_STOCKS_COL.delete_one({'stock_code': stock_code})
    return StandardResponseItem()


async def get_stocks():
    async for item in ATTENTION_STOCKS_COL.find({}):
        yield item['stock_code']


@router.get("/get_trade_detail")
async def get_trade_detail(code: str = "",count=10):
    cookies = await get_cookies()
    async with AsyncSession(impersonate="chrome110", cookies=cookies) as session:
        results = await get_trade(session, code,count)
    return StandardResponseItem(data=results)


@router.get("/get_data")
async def get_data(codes: str = ""):
    cookies = await get_cookies()
    async with AsyncSession(impersonate="chrome110", cookies=cookies) as session:
        if not codes:
            codes = [code async for code in get_stocks()]
        else:
            codes = codes.split(",")
        results = await realtime_quotec(session, codes)
        for i in results:
            stock_name = await get_stock_name(i['symbol'])
            i['stock_name'] = stock_name

    return StandardResponseItem(data=results)


@router.get("/comment")
async def get_comment(code, page: int = 1, page_size: int = 10):
    cookies = await get_cookies()
    async with AsyncSession(impersonate="chrome110", cookies=cookies) as session:
        results = await comment(session, code, page, page_size)

    return StandardResponseItem(data=results)


@router.get('/suggest')
async def suggest(q: str):
    cookies = await get_cookies()
    async with AsyncSession(impersonate=chrome_version.CHROME124, cookies=cookies) as session:
        results = await suggest_stock(session, q)
    return StandardResponseItem(data=results)


@router.get("/user_timeline")
async def get_user_timeline(page: int = 1, user_id: str = "1218465053"):
    cookies = await get_cookies()
    async with AsyncSession(impersonate="chrome110", cookies=cookies) as session:
        results = await user_timeline(session,  page, user_id=user_id)

    return StandardResponseItem(data=results)


@router.get("/monitor")
async def monitor():
    async with AsyncSession(impersonate="chrome110", headers={
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 12; SM-A5260 Build/588af81.0)',
        'Connection': 'Keep-Alive',
    }) as session:

        data = {
            'a': 'Radar',
            'st': '30',
            'apiv': 'w39',
            'c': 'HomeDingPan',
            'PhoneOSNew': '1',
            'DeviceID': '50ee3708-cac5-3b09-88b6-d290d7e5026a',
            'VerSion': '5.18.0.4',
            'Index': '30',
        }
        response = await session.post('https://apphwhq.longhuvip.com/w1/api/index.php', data=data)

    return StandardResponseItem(data=response.json())
